package com.opages.mvc.adapter.consul.discovery;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.HealthService;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.opages.mvc.adapter.common.client.ServiceInstance;
import com.opages.mvc.adapter.common.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author daizhong.liu
 * @create 2020-03-02 10:49
 **/
public class ConsulDiscoveryClient implements DiscoveryClient {
    /** consul配置信息 */
    @Value("${spring.mvc.consul.host}")
    private String consulHost;
    @Value("${spring.mvc.consul.port:8500}")
    private Integer consulPort;

    @Override
    public List<ServiceInstance> getInstances(String serviceId) {
        try {
            if(StringUtils.isEmpty(consulHost)) {
                throw new RuntimeException("未配置consul.server.url注册中心地址!");
            }
            ConsulClient client = new ConsulClient(consulHost, consulPort);
            Response<List<HealthService>> catalogServiceList = client.getHealthServices(serviceId, true, null);
            List<HealthService> list = catalogServiceList.getValue();
            if (list == null || list.isEmpty()) {
                return null;
            }
            List<ServiceInstance> servers = new ArrayList<ServiceInstance>();
            for (HealthService item : list) {
                servers.add(new ConsulServiceInstance(item));
            }
            return servers;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public ServiceInstance chooseServer(String serviceId) {
        try {
            if(StringUtils.isEmpty(consulHost)) {
                throw new RuntimeException("未配置consul.server.url注册中心地址!");
            }
            ConsulClient client = new ConsulClient(consulHost, consulPort);
            Response<List<HealthService>> catalogServiceList = client.getHealthServices(serviceId, true, null);
            List<HealthService> list = catalogServiceList.getValue();
            if (list == null || list.isEmpty()) {
                return null;
            }
            ILoadBalancer balancer = new BaseLoadBalancer();
            List<Server> servers = new ArrayList<Server>();
            for (HealthService item : list) {
                servers.add(new ConsulServiceInstance(item));
            }
            balancer.addServers(servers);
            ConsulServiceInstance choosedServer = (ConsulServiceInstance)balancer.chooseServer(null);
            return choosedServer;
        } catch (Exception e) {
            return null;
        }
    }
}
